import { Form, Card, Button } from 'antd';
import React, { Component } from 'react';
import { FormComponentProps } from 'antd/es/form';
import { Dispatch } from 'redux';
import { StateType } from './model';
import { TableListItem, TableListPagination, TableListParams, FormItem } from './data.d';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import styles from './style.less';
import StandardTable, { StandardTableColumnProps } from '@/components/StandardTable';
import { SorterResult } from 'antd/es/table';
import { connect } from 'dva';
import Constants from '../applyAmount/utils/Constants';
import ApplyAmountForm from './components/ApplyAmountForm';
import { download } from '../applyAmount/utils/commons';

interface TableListProps extends FormComponentProps {
  dispatch: Dispatch<any>;
  loading: boolean;
  applyAmount: StateType;
}

interface TableListState {
  modalVisible: boolean;
  selectedRows: TableListItem[];
  formValues: Partial<FormItem>;
  disabled: boolean;
  showDetail: boolean;
}

// const getValue = (obj: { [x: string]: string[] }) =>
//   Object.keys(obj)
//     .map(key => obj[key])
//     .join(',');

@connect(
  ({
    applyAmount,
    loading,
    global,
  }: {
    applyAmount: StateType;
    global: StateType;
    loading: {
      models: {
        [key: string]: boolean;
      };
    };
  }) => ({
    applyAmount,
    global,
    loading: loading.models.applyAmount,
  }),
)
class TableList extends Component<TableListProps, TableListState> {

  state: TableListState = {
    modalVisible: false,
    selectedRows: [],
    formValues: {},
    disabled: false,
    showDetail: true
  };

  columns: StandardTableColumnProps[] = [
    {
      title: '申请单号',
      dataIndex: 'id',
      render: (val: string) => <span>{`ZBT-WS-APPLYAMOUNT-${val}`}</span>,
    },
    {
      title: '债务人姓名',
      dataIndex: 'debtorName',
    },
    {
      title: '债务联系人',
      dataIndex: 'debtorLinkman',
    },
    {
      title: '债务人电话',
      dataIndex: 'debtorMobile',
    },
    {
      title: '债务人邮箱',
      dataIndex: 'debtorEmail',
    },
    {
      title: '应收金额',
      dataIndex: 'revAmount',
    },
    {
      title: '债权人姓名',
      dataIndex: 'creditorName',
    },
    {
      title: '债权联系人',
      dataIndex: 'creditorLinkman',
    },
    {
      title: '债权人电话',
      dataIndex: 'creditorMobile',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (val: string) => <span>{Constants.STATUS[val]}</span>
    },
    // {
    //   title: '操作',
    //   render: (text, record) => (
    //     <Fragment>
    //       <a onClick={() => this.handleUpdateModalVisible(true, record, true)}>详情</a>
    //       <Divider type="vertical" />
    //     </Fragment>
    //   ),
    // },
  ];

  handleModalVisible = (flag?: boolean, record?: TableListItem) => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  handleSelectRows = (rows: TableListItem[]) => {
    this.setState({
      selectedRows: rows,
    });
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'applyAmount/fetch',
      payload: {
        page: Constants.DEFAULT_PAGE.page,
        size: Constants.DEFAULT_PAGE.size
      }
    });
  }

  handleStandardTableChange = (pagination: Partial<TableListPagination>, filtersArg: Record<keyof TableListItem, string[]>, sorter: SorterResult<TableListItem>) => {
    const { dispatch } = this.props;

    // const filters = Object.keys(filtersArg).reduce((obj, key) => {
    //   const newObj = { ...obj };
    //   newObj[key] = getValue(filtersArg[key]);
    //   return newObj;
    // }, {});

    const params: Partial<TableListParams> = {
      page: pagination.current,
      size: pagination.pageSize
    };
    // if (sorter.field) {
    //   params.sorter = `${sorter.field}_${sorter.order}`;
    // }

    dispatch({
      type: 'applyAmount/fetch',
      payload: params,
    });
  };

  handleUpdateModalVisible = (flag?: boolean, record?: Partial<TableListItem>, disabled?: boolean) => {
    this.setState({ modalVisible: !!flag, formValues: {}, disabled: !!disabled });
    if (record) {
      const { dispatch } = this.props;
      dispatch({
        type: 'applyAmount/get', payload: {
          id: record.id,
          onSuccess: (data?: Partial<FormItem>) => {
            this.setState({ formValues: data || {}, disabled: !!disabled });
          }
        }
      });
    }
  };

  handleSave = (fields: FormItem) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'applyAmount/add',
      payload: {
        ...fields,
        onSuccess: () => {
          this.handleUpdateModalVisible();
          const { dispatch } = this.props;
          dispatch({
            type: 'applyAmount/fetch',
            payload: {
              page: Constants.DEFAULT_PAGE.page,
              size: Constants.DEFAULT_PAGE.size
            }
          });
        }
      },
    });
  };

  render() {

    const { applyAmount: { data }, loading } = this.props;

    const { selectedRows, modalVisible, formValues, disabled, showDetail } = this.state;

    const methods = {
      handleUpdateModalVisible: this.handleUpdateModalVisible,
      handleSave: this.handleSave,
    };

    return (
      <PageHeaderWrapper content={<div style={{ textAlign: 'center' }}>
        <Button key="detail" type="primary" onClick={() => this.setState({ showDetail: !showDetail })}>{showDetail ? "收起" : "展开说明"}</Button>
        <div style={{ display: showDetail ? 'block' : 'none', marginTop: 10 }}>
          <div>
            <b>产品说明(Product)</b><br />
            我们通过合法合规的方式，为客户在全球范围内追索被拖欠的应收账款。<br />
            We pursue arrears of accounts receivable on a global basis for our clients in a lawful and compliant manner.
            </div>
          <br />
          <div>
            <b>产品优势(Advantage)</b><br />
            覆盖全球200个国家和地区。<br />
            The collection service network covers nearly 200 countries/regions in the world.<br />
            前期0费用，款项回到您的账户后再支付相关手续费。<br />
            All the handling fee will be charged only when your accounts receivable returned.<br />
            我们的成功率高达80%。<br />
            Our success rate is nearly 80%.
            </div>
          <br />
          <div>
            <b>收费标准(Cost)</b><br />
            手续费用低至30%!<br />
            Handling fee as low as 30%!
          </div>
          <div>
            <b><a onClick={() => download(PORTAL_PATH + '/api/file/download', { filename: 'attachment/广州市丑寅商业保理有限公司-全球催收协议.pdf' })}>全球催收协议(下载)</a></b>
            <b style={{ marginLeft: 10 }}><a onClick={() => download(PORTAL_PATH + '/api/file/download', { filename: 'attachment/国家列表和收费标准.pdf' })}>国家列表和收费标准(下载)</a></b>
          </div>
        </div>
      </div>}>
        <Card bordered={false}>
          {
            modalVisible ?
              <ApplyAmountForm
                {...methods}
                data={formValues}
                disabled={disabled}
              /> :
              <div className={styles.tableList}>
                <div className={styles.tableListOperator}>
                  <Button icon="plus" type="primary" onClick={() => this.handleUpdateModalVisible(true)}>立即申请</Button>
                </div>
                <StandardTable
                  selectedRows={selectedRows}
                  loading={loading}
                  data={data}
                  columns={this.columns}
                  onSelectRow={this.handleSelectRows}
                  onChange={this.handleStandardTableChange}
                />
              </div>
          }

        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default Form.create<TableListProps>()(TableList);
